import { Navigate, useSearchParams } from "react-router-dom";
import { useLazyOrderDetailQuery } from "@store/apiSlice/consultApiSlice";
import React, { useEffect } from "react";
import { OrderStatus } from "@enums/consult";

interface Props {
  children: React.ReactElement;
}

export default function RoomGuardRoute({ children }: Props) {
  // 获取路由参数
  const [searchParams] = useSearchParams();
  // 获取订单id
  const orderId = searchParams.get("orderId");
  // 用于获取订单详细信息
  const [requestOrder, { isSuccess, data }] = useLazyOrderDetailQuery();

  useEffect(() => {
    // 如果 orderId 存在
    if (orderId !== null) {
      // 获取订单详情
      requestOrder(orderId);
    }
  }, [orderId, requestOrder]);

  // 订单 id 不存在
  if (orderId === null) return <Navigate to="/" />;
  // 如果订单详情没有获取成功, 暂时什么都不渲染
  if (!isSuccess) return null;

  // 如果订单状态不是待支付, 允许进入问诊室, 否则跳转到首页
  return data?.data.status !== OrderStatus.ConsultPay ? (
    children
  ) : (
    <Navigate to="/" />
  );
}